import Vue from 'vue'
import VueRouter from 'vue-router'

import MyLogin from '@/components/MyLogin.vue'

Vue.use(VueRouter)

const routes = [
  // 数组中最大级别的路由，叫做一级路由
  // 一级路由对应的组件，要显示到App中
  { path: '/', redirect: '/login' },
  { path: '/login', component: MyLogin },
  {
    path: '/home',
    redirect: '/home/users',
    component: () => import('@/components/MyHome.vue'),
    children: [
      {
        path: 'goods',
        component: () => import('@/components/menus/MyGoods.vue')
      },
      {
        path: 'orders',
        component: () => import('@/components/menus/MyOrders.vue')
      },
      {
        path: 'rights',
        component: () => import('@/components/menus/MyRights')
      },
      {
        path: 'settings',
        component: () => import('@/components/menus/MySettings.vue')
      },
      {
        path: 'users',
        component: () => import('@/components/menus/MyUsers.vue')
      },
      {
        path: 'detail/:id',
        component: () => import('@/components/user/MyUserDetail.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 必须在这里，添加全局前置导航守卫
router.beforeEach((to, from, next) => {
  // to 到哪里去   to.path 表示你想去的那个路由地址
  // from 从哪里来 from.path 表示跳转之前的那个地址
  // next() 表示放行，运行访问；   next(false) 不允许放行，哪也不跳转    next('/login') 强行跳转到指定的地址
  if (to.path === '/login') {
    next() // 访问登录页，直接运行访问，放行
  } else {
    // 说明访问的不是登录页
    if (localStorage.getItem('token')) {
      next()
    } else {
      // 访问的不是登录页，本地存储也没有token(没有正常登录)
      next('/login')
    }
  }
})

export default router
